from rest_framework import serializers
from django.contrib.auth import get_user_model
import uuid

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'phone', 'avatar', 'openid']
        read_only_fields = ['openid']

class UserRegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['phone', 'openid', 'avatar']

    def create(self, validated_data):
        # 生成一个唯一的用户名（使用uuid前8位）
        username = f"user_{str(uuid.uuid4())[:8]}"
        user = User.objects.create_user(
            username=username,
            phone=validated_data['phone'],
            openid=validated_data['openid'],
            avatar=validated_data.get('avatar', '')
        )
        return user 